/**
 * create by young (young2f@outlook.com) on 2020/10/28
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Card, Divider, Drawer, Form, Layout, List, Popconfirm, Table, Tag} from 'antd';
import styles from '../card.less';
import {getMenuData} from '../../common/menu';
import ViewTitle from '../../components/ViewTitle';
import {ModalView} from 'antd-extra';
import ComponentBase from '../../components/Base/ComponentBase';
import ModalAddQuicklyMenu from './modals/ModalAddQuicklyMenu';
import echarts from 'echarts';
import {routerRedux} from 'dva/router';
import {value} from "lodash/seq";
import moment from "moment";
import ModalCreateOrEditWork from "../work/modal/ModalCreateOrEditWork";
import ModalWorkDetail from "../work/modal/ModalWorkDetail";

const {Content, Sider} = Layout;

const _ = require('lodash');

@Form.create()
@connect(({global, store, work, user}) => ({...global, ...store, ...work, ...user}))
export default class Index extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    // this.props.dispatch(
    //   {type: 'store/desktop', payload: {}}
    // );
    //
    // const {userCode, username, userType} = this.getLoginInfo();
    // this.props.dispatch(
    //   {type: 'work/findWorkMany', payload: {userCode,username,userType}}
    // );
  }

  async onLoadData() {
    // const res = await this.props.dispatch(
    //   {type: 'device/deviceStatistics', payload: {}}
    // );
    // const {result = {}} = res;
    // return {...result};
  }

  getFlatMenuKeys = (menu, array) =>
    menu.reduce((keys, item) => {
      if (item) {
        if (item.path !== '/desktop') {
          array.push(item);
        }
        if (item.children) {
          this.getFlatMenuKeys(item.children, array);
        }
      }
    }, []);

  columns = () => {
    // const model = this.props[`${table}Model`];
    // if (!model) return [];

    // const temp = this.getTableColumns(model);
    const temp = [];
    temp.push(
      {title: '任务编码', dataIndex: 'code', key: 'code'},
      {title: '创建人', dataIndex: 'createUsername', key: 'createUsername'},
      {title: '责任人', dataIndex: 'username', key: 'username'},
      {title: '事项', dataIndex: 'desc', key: 'desc', ellipsis: true},
      {
        title: '要求完成时间',
        dataIndex: 'requiredCompletionDate',
        key: 'requiredCompletionDate',
        render: (text, record) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      {
        title: '实际完成时间',
        dataIndex: 'completionDate',
        key: 'completionDate',
        render: (text, record) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      {
        title: '完成情况',
        dataIndex: 'completionDesc',
        key: 'completionDesc', ellipsis: true
      },

      {
        title: '是否逾期', dataIndex: 'isOverdue', key: 'isOverdue',
        render: (value, record) => {
          const {completionDate, requiredCompletionDate,isEnded} = record;
          const day1 = moment(requiredCompletionDate).format('YYYY-MM-DD');
          const day2 = moment().format('YYYY-MM-DD');

          let _str = moment(day2).valueOf() > moment(day1).valueOf() ? <Tag color={'#f00'}>已逾期</Tag> :
            <Tag color={'#00f'}>未逾期</Tag>;
          let str = isEnded ? <Tag color={'#0f0'}>已完成</Tag> : _str;
          return <div>{str}</div>;
        }
      }, {
        title: '是否完成', dataIndex: 'isEnded', key: 'isEnded',
        render: (value) => {
          return value ? <Tag color={'#0f0'}>是</Tag> : <Tag color={'#555'}>否</Tag>;
        }
      },
      );

    return temp;
  };

  onDeviceDetailClick() {
    this.props.dispatch(routerRedux.push({pathname: '/device/list'}));
  }

  cardHandle = (item) => {
    let {title, value} = item;
    if (value === undefined) {
      value = '-';
    }
    return (
      <List.Item style={{marginRight: '12px'}}>
        <Card.Grid style={{width: '100%', height: '140px', marginBottom: '12px', 'text-align': 'center'}}>
          <div style={{fontSize: 16, fontWeight: 550, textAlign: 'left'}}>
            {title}
          </div>
          <a style={{fontSize: 48, fontWeight: 550}}
            // href={'#/store/index'}
          >
            {value}
          </a>
        </Card.Grid>
      </List.Item>
    );
  };

  render() {
    const {loading, myMsgs = []} = this.state;
    const {showDetail, record} = this.state;
    const {dispatch, data = {}, works = []} = this.props;
    const {materialCount = 0, storeCount = 0, amount = 0} = data;
    const loginInfo = wStore.getStore('loginInfo');

    const {role, userType, quicklyMenus = []} = loginInfo;
    if (userType === 'su') {
      return (<div>欢迎超级管理员</div>);
    }
    const {menus} = role;
    const allMainMenu = getMenuData();

    const allMenus = [];
    allMainMenu.map(item => {
      const {children} = item;
      children && children.map(child => {
        allMenus.push(child);
      });
    });

    const myMenus = [];
    allMenus.map(item => {
      const {path} = item;
      if (_.includes(menus, path)) {
        myMenus.push(item);
      }
    });
    if (!_.find(quicklyMenus, item => item.isAdd)) {
      quicklyMenus.push({title: '', path: '/add', isAdd: true});
    }
    const devices = [
      {title: '物料总数量', value: materialCount},
      {title: '库存总数量', value: storeCount},
      {title: '库存总金额（元）', value: amount}
    ];
    return (
      <Form className={styles.content}>
        {/*<Layout className={styles.content}>*/}
        {/*  <Sider className={styles.content} width="80%">*/}
        {/*    /!*<ViewTitle title={'库存统计'}*!/*/}
        {/*    /!*></ViewTitle>*!/*/}
        {/*    /!*<div style={{width: '100%', marginTop: '26px'}}>*!/*/}
        {/*    /!*  <List grid={{column: 4}}*!/*/}
        {/*    /!*        dataSource={devices}*!/*/}
        {/*    /!*        renderItem={item => (<span>   {this.cardHandle(item)}  </span>)}*!/*/}
        {/*    /!*  />*!/*/}
        {/*    /!*</div>*!/*/}

        {/*    /!*<Divider dashed/>*!/*/}

        {/*    /!*<ViewTitle title={'设备数据统计'}></ViewTitle>*!/*/}
        {/*    /!*<div ref={(c) => {*!/*/}
        {/*    /!*  this.deviceDataReportCharts = c;*!/*/}
        {/*    /!*}} style={{width: '110%', height: 300}}>*!/*/}
        {/*    /!*</div>*!/*/}
        {/*    <ViewTitle title={'我的工作任务'}></ViewTitle>*/}
        {/*    <Table*/}
        {/*      loading={loading}*/}
        {/*      className={styles.antTable}*/}
        {/*      bordered={true}*/}
        {/*      columns={this.columns()}*/}
        {/*      dataSource={works}*/}
        {/*    ></Table>*/}
        {/*  </Sider>*/}

        {/*  <Content className={styles.content}>*/}
            <ViewTitle title={'常用菜单'}> </ViewTitle>
            <List
              grid={{gutter: 1, column: 5}}
              style={{margin: 32}}
              dataSource={quicklyMenus}
              renderItem={item => (
                <List.Item>
                  <Button type={item.isAdd ? 'dashed' : 'primary'}
                          // shape="circle"
                          style={{width: 48, height: 48, marginBottom: 8, marginTop: 12}}
                          size={'large'}
                          onClick={() => {
                            const {path, isAdd} = item;
                            if (isAdd) {
                              ModalView.open(ModalAddQuicklyMenu,
                                {title: '添加常用菜单', width: '720px'},
                                {
                                  menus: myMenus,
                                  quicklyMenus,
                                  callback: async quicklyMenus => {
                                    const {username} = loginInfo;
                                    const user = {username, quicklyMenus};
                                    console.log('selectedKeysselectedKeys', user);
                                    const res = await dispatch(
                                      {type: 'user/updateUser', payload: {...user}}
                                    );
                                    console.log('ress', res);
                                    const loginUser = wStore.getStore('loginInfo');
                                    loginUser.quicklyMenus = quicklyMenus;
                                    wStore.setStore('loginInfo', loginUser);
                                    this.requestReturn(res);
                                    this.componentDidMount();
                                  }
                                });
                              return;
                            }
                            this.props.history.push(path);
                            const {subMenuOpen} = this.state;
                            this.state.subMenuOpen = !subMenuOpen;
                          }}>{item.isAdd ? '+' : item.title.substring(0, 1)}</Button>
                  <div>{item.title}</div>
                </List.Item>
              )}
            />
        {/*  </Content>*/}
        {/*</Layout>*/}
        {/*{showDetail && <Drawer*/}
        {/*  visible={showDetail}*/}
        {/*  title={`工作任务`}*/}
        {/*  placement="left"*/}
        {/*  width={'80%'}*/}
        {/*  style={{padding: 0}}*/}
        {/*  // maskClosable={false}*/}
        {/*  onClose={() => {*/}
        {/*    this.setState({showDetail: false});*/}
        {/*    this.componentDidMount();*/}
        {/*  }}*/}
        {/*>*/}
        {/*  <ModalWorkDetail*/}
        {/*    record={record}*/}
        {/*  > </ModalWorkDetail>*/}
        {/*</Drawer>}*/}
      </Form>
    );
  }
}
